/* 库存调货页面
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\InventoryTransfer\List\index.tsx
 * @Date: 2021-12-03 14:15:21
 * @LastEditTime: 2021-12-03 17:15:19
 */
import React from 'react'
import {
  BaseListPage,
  IBaseListPageState,
  IBaseListPageProps,
  columnRenders,
  UdDrawer,
  UdMonthPicker,
  UdModal,
  UdModalForm,
  validators,
  http,
  uaaApp,
} from '@/lib'
import { Select, Button, Modal, message, Upload, Tooltip } from 'antd'
import apis from '@/apis/AboutQuota'
import udMainStore from '@/store/UdMain'
import EditInventoryTransfer from '../components/EditInventoryTransfer'
import AddInventoryTransfer from '../components/AddInventoryTransfer'
import UdSelect from '@/components/UdFormControls/UdSelect'
import { downBlobFile, downBlobFileXlsx } from '@/utils/methods'
import ImportExcelForm from '../components/ImportExcelForm'
const { Option } = Select
const confirm = Modal.confirm
const addBtn = 'quota_employee_manager_InventoryTransfer_add' //新增
const importBtn = 'quota_employee_manager_InventoryTransfer_import' //导入
const downTemplateBtn = 'quota_employee_manager_InventoryTransfer_download_template' //下载模板
const tableEditBtn = 'quota_employee_manager_InventoryTransfer_edit' //列表操作-编辑
const tableDeleteBtn = 'quota_employee_manager_InventoryTransfer_delete' //列表操作-删除
export default class InventoryTransfer extends BaseListPage<ApplicationFormListProps, ApplicationFormListState> {
  // 隐藏掉头曲二曲
  // public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  // public brandCompanies = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  public brandCompanies = udMainStore.brandList
  protected useConditionsField = true
  constructor(props) {
    super(props)
    this.state = {
      title: '库存调货',
      rowKey: 'id',
      queryApi: apis.getCheckTransferList,
      method: 'POST',
      conditions: [
        {
          id: 'brandCode',
          label: '品牌公司',
          initialValue: this.brandCompanies[0].value,
          render: () => (
            <Select placeholder="请选择品牌公司">
              {this.brandCompanies.map(({ value, title }) => (
                <Option key={value} value={value}>
                  {title}
                </Option>
              ))}
            </Select>
          ),
        },
        {
          id: 'prodBarcode',
          label: '物料编码',
        },
        {
          id: 'prodName',
          label: '物料描述',
        },
        {
          id: 'inventoryCycle',
          label: '盘点周期',
          render: () => (
            <UdMonthPicker
              placeholder="请选择盘点周期"
              style={{ width: '100%' }}
              className={'ext'}
            />
          ),
        },
        {
          id: 'dealerCode',
          label: '客户编码',
        },
        {
          id: 'dealerName',
          label: '客户名称',
        },
      ],
      columns: [
        { title: '序号', key: 'id', dataIndex: 'id', minWidth: '40px', render: (text, recode, index) => index + 1 },
        {
          title: '品牌公司',
          key: 'brandName',
          dataIndex: 'brandName',
          minWidth: '140px',
        },
        {
          title: '物料编码',
          key: 'prodBarcode',
          dataIndex: 'prodBarcode',
          minWidth: '140px',
        },
        {
          title: '物料描述',
          key: 'prodName',
          dataIndex: 'prodName',
          minWidth: '140px',
        },
        {
          title: '客户编码',
          key: 'dealerCode',
          dataIndex: 'dealerCode',
          minWidth: '120px',
        },
        {
          title: '客户名称',
          key: 'dealerName',
          dataIndex: 'dealerName',
          minWidth: '140px',
        },
        {
          title: '盘点周期',
          key: 'inventoryCycle',
          dataIndex: 'inventoryCycle',
          minWidth: '120px',
        },
        {
          title: '调入调出',
          key: 'number',
          dataIndex: 'number',
          minWidth: '50px',
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          minWidth: '80px',
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          minWidth: '120px',
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 180,
          render: (text, record) => {
            return (
              <Tooltip title={record.remark}>
                <div style={{ width: '180px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {record.remark}
                </div>
              </Tooltip>
            )
          },
        },

        {
          title: '操作',
          dataIndex: 'operate',
          fixedWidth: '120px',
          fixed: 'right',
          render: columnRenders.operate([
            {
              title: '编辑',
              auth: tableEditBtn,
              action: (text, record) => {
                this.handEdit(record)
              },
            },
            {
              title: '删除',
              auth: tableDeleteBtn,
              action: (text, record) => {
                confirm({
                  title: '确定要删除该数据吗?',
                  onOk: () => {
                    return this.handDelete(record)
                  },
                })
              },
            },
          ]),
        },
      ],
      leftBtns: [
        uaaApp.canUse(addBtn) && (
          <Button
            type="primary"
            onClick={() => {
              this.handAdd()
            }}
          >
            新增
          </Button>
        ),
        uaaApp.canUse(importBtn) && (
          <Button
            type="primary"
            onClick={() => {
              this.handImportExcel()
            }}
          >
            导入
          </Button>
        ),
        uaaApp.canUse(downTemplateBtn) && (
          <Button
            type="primary"
            onClick={() => {
              this.handDownloadTemplate()
            }}
          >
            下载模板
          </Button>
        ),
      ],
      tableProps: {
        rowSelection: null,
        scroll: { x: true },
      },
      fileList: [],
    }
  }

  private handDownloadTemplate = () => {
    UdModal.open({
      title: '下载模板',
      maskClosable: false,
      content: (
        <UdModalForm
          items={[
            {
              label: '品牌公司',
              id: 'brand',
              rules: [validators.required],
              render: <UdSelect showSearch labelInValue options={this.brandCompanies} onChange={value => {}} />,
            },
            {
              id: 'inventoryCycle',
              label: '盘点周期',
              rules: [validators.required],
              render: (
                <UdMonthPicker
                  onChange={() => {}}
                  placeholder="请选择盘点周期"
                  style={{ width: '100%' }}
                  className={'ext'}
                />
              ),
            },
          ]}
        />
      ),
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        return this.downloadTemplate(values)
      },
    })
  }

  //下载模板
  private downloadTemplate = values => {
    let params = {}
    params['brandCode'] = values.brand.key
    params['brandName'] = values.brand.label
    params['inventoryCycle'] = values.inventoryCycle
    return http.get(apis.inventoryTransferExport, { params, responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFileXlsx(res.data, '库存调货模板')
      } else {
        return Promise.reject()
      }
    })
  }

  //导入文件
  private handImportExcel = () => {
    UdModal.open({
      title: '导入文件',
      maskClosable: false,
      content: <ImportExcelForm />,
      okText: '确定',
      cancelText: '取消',
      onOk: values => {
        let { file: fileList } = values
        return this.importExcel(fileList?.[0]?.originFileObj)
      },
    })
  }

  //文件上传
  private importExcel = excelFile => {
    if (!excelFile) return
    const formData = new FormData()
    formData.append('file', excelFile)
    return http.post(apis.inventoryTransferImport, formData, { timeout: 1000 * 60 * 10 }).then(() => {
      message.success('操作成功')
      this.query()
    })
  }

  private handAdd = () => {
    UdDrawer.open({
      title: '新增库存调货',
      width: '40%',
      content: <AddInventoryTransfer brandCompanies={this.brandCompanies} />,
      onSubmit: () => {
        this.query()
      },
    })
  }

  //删除
  private handDelete = (record: any) => {
    http.post(apis.delCheckTransfer, { id: record.id }).then(() => {
      message.success('操作成功')
      this.query()
    })
  }
  //编辑
  private handEdit = (record: any) => {
    UdDrawer.open({
      title: `编辑`,
      width: '50%',
      content: <EditInventoryTransfer record={record} />,
      onSubmit: () => {
        this.query()
      },
    })
  }
}

interface ApplicationFormListState extends IBaseListPageState {
  fileList?: any
}

interface ApplicationFormListProps extends IBaseListPageProps {}
